// CandidataZone.js
import ScreenPositionUtil from "./ScreenPositionUtil";
import ConstStrings from "./datas/strings";
import GameConfig from "./GameConfig";

// 显示区域宽高
var candidateZoneMarginTopRatio = 0.02;

var candidateZoneStartX = 0;
var candidateZoneStartY = 0;
var candidateZoneWHRatio = 2.2;
var candidateZoneWID = 0;
var candidateZoneHEI = 0;


var candidateZoneMarginLeftRight = 0;
var candidateZoneMarginButtom = 400;
var candidateZoneMarginUp = 0;

var candidateItemSumH = 4;
var candidateItemSumV = 2;

var candidateItemWID = 0;
var candidateItemHEI = 0;

/**
 * 
 */
export default class CandidataZone extends Laya.Sprite {
    constructor(lastViewEndPos) {
        super();

        // 候选区域数据
        this.candidateDatas = [];
        // 父组件 用于回调父类方法
        this.sceneParent = null;

        // 候选区起始位置
        candidateZoneStartX = 0 + candidateZoneMarginLeftRight; // 展示区起始位置
        candidateZoneStartY = lastViewEndPos.y + ScreenPositionUtil.getPostionInStage(candidateZoneMarginTopRatio , "y"); // 展示区起始位置

        // 候选区宽、高
        candidateZoneWID = Laya.stage.width - (candidateZoneMarginLeftRight * 2);
        let targetHeight = candidateZoneWID / candidateZoneWHRatio;
        if(candidateZoneStartY + targetHeight < Laya.stage.height)
            candidateZoneHEI = targetHeight;
        else 
            candidateZoneHEI = Laya.stage.height - candidateZoneStartY;

        // 候选item起始宽、高
        candidateItemWID = candidateZoneWID / candidateItemSumH;
        candidateItemHEI = candidateZoneHEI / candidateItemSumV;
        candidateZoneMarginUp = 840;

        this.size(candidateZoneWID, candidateZoneHEI);
        this.pos(candidateZoneStartX, candidateZoneStartY);

        Laya.stage.graphics.drawRect(0, lastViewEndPos.y, candidateZoneWID, Laya.stage.height - lastViewEndPos.y, "#ffffff");
        // 列表
        this.viewCandidateList = {};
    }

    /**
     * list  鼠标选中
     * @param {*} e 
     * @param {*} index 
     */
    onCandidateSelect(e, index) {
        if(GameConfig.isUnableTouch)
            return;

        if (e.type != "mousedown")
            return;

        let tempClickCell = null;
        let tempClickCellView = null;

        for (let i = 0; i < this.candidateDatas.candidateParts.length; i++) {
            let tempCell = this.candidateDatas.candidateParts[i];

            if (i != index)
                tempCell.isSelect = false;
            else {
                tempClickCell = tempCell;
            }
        }

        if (tempClickCell.isRight) {
            this.sceneParent.onCandidateSelect(this.candidateDatas.candidateParts[index]);
            tempClickCell.isSelect = true;
        } else {
            this.sceneParent.onCandidateSelect(null);
            tempClickCell.isSelect = false;
            tempClickCell.needWrongTwinkle = true; // 错误动画
        }

        this.viewCandidateList.refresh();
    }

    /**
     * list  ui更新
     * @param {*} e 
     * @param {*} index 
     */
    updateCandidateItem(cell, index) {
        cell.updateViewByData(cell.dataSource);
    }

    /**
     * 初始化候选区域数据
     * @param {*} e 
     * @param {*} index 
     */
    setCandidateDataList(e) {
        this.destroyChildren();
        this.candidateDatas = e;

        this.viewCandidateList = new Laya.List();
        this.addChild(this.viewCandidateList);
        this.viewCandidateList.itemRender = CandidateItemView;
        this.viewCandidateList.repeatX = candidateItemSumH;
        this.viewCandidateList.repeatY = candidateItemSumV;

        this.viewCandidateList.mouseHandler = new Laya.Handler(this, this.onCandidateSelect);
        this.viewCandidateList.renderHandler = new Laya.Handler(this, this.updateCandidateItem);
        this.viewCandidateList.array = this.candidateDatas.candidateParts;
    }

    /**
     * 设置父组件
     * @param {*} e 
     */
    setSceneParent(e) {
        this.sceneParent = e;
    }
}

class CandidateItemView extends Laya.Box {
    constructor() {
        super();
        this.dataCandidateItem = {};

        this.viewImage = {};
        this.size(candidateItemWID, candidateItemHEI);
        this.circleRadius = Math.min(candidateItemWID , candidateItemHEI) / 3.7;

        // 颜色圆
        this.viewImage = new Laya.Sprite();
        this.viewImage.size(candidateItemWID, candidateItemHEI);
        this.addChild(this.viewImage);
        // this.viewImage.graphics.drawCircle(candidateItemWID / 2, candidateItemHEI / 2,
        //     this.circleRadius, "#00ffff");

        // 圆边框
        this.viewImageBorder = new Laya.Sprite();
        this.viewImageBorder.size(candidateItemWID, candidateItemHEI);
        this.addChild(this.viewImageBorder);
        this.viewImageBorder.graphics.drawCircle(candidateItemWID / 2, candidateItemHEI / 2,
            this.circleRadius * 1.0, "#00000000", "#A6A6A6");
        this.viewImageBorder.visible = false;

        // 选中边框
        this.viewSelect = new Laya.Sprite();
        this.viewSelect.size(this.circleRadius * 2.3 ,this.circleRadius * 2.3 );
        this.viewSelect.pivot(this.viewSelect.width / 2, this.viewSelect.height / 2);
        this.viewSelect.pos(candidateItemWID / 2, candidateItemHEI / 2);
        this.addChild(this.viewSelect);
        this.viewSelect.loadImage(ConstStrings.circle);
        this.viewSelect.alpha = 0;

        // 选中标志
        this.viewSelectSign = new Laya.Sprite();
        this.viewSelectSign.size(this.circleRadius * 2 , this.circleRadius * 2);
        this.viewSelectSign.pivot(this.viewSelectSign.width / 2, this.viewSelectSign.height / 2);
        this.viewSelectSign.loadImage("res/scene/material-puzzle/select_right_dark.png");
        this.addChild(this.viewSelectSign);
        this.viewSelectSign.pos(candidateItemWID / 2, candidateItemHEI / 2);
        this.viewSelectSign.alpha = 0 ;

    }

    updateViewByData(e) {
        this.dataCandidateItem = e;
        this.setFillColor(e.color); // 画圆
        this.updateSelectState(e.isSelect); // 更新选中
        if (e.needWrongTwinkle) {
            this.doSelectWrongTwinkle();
            e.needWrongTwinkle = false;
        }

        if(e.color == "#FFFFFF")
            this.viewImageBorder.visible = true;
        else 
            this.viewImageBorder.visible = false;
    }

    updateSelectState(e) {
        if (e) {
            Laya.Tween.to(this.viewSelect, { alpha: 1 }, 800, Laya.Ease.quartOut);

            if(this.checkIsLight())
                this.viewSelectSign.loadImage(ConstStrings.candidateSelectLight);
            else
                this.viewSelectSign.loadImage(ConstStrings.candidateSelectDark);
            Laya.Tween.to(this.viewSelectSign, { alpha: 1 }, 800, Laya.Ease.quartOut);
        }
        else {
            if (this.viewSelect.alpha != 0)             
                Laya.Tween.to(this.viewSelect, { alpha: 0 }, 800, Laya.Ease.quartOut);
            if (this.viewSelectSign.alpha != 0)             
                Laya.Tween.to(this.viewSelectSign, { alpha: 0 }, 800, Laya.Ease.quartOut);
        }
    }

    setFillColor(e) {
        // this.viewImage.graphics.destroy();
        this.viewImage.graphics.drawCircle(candidateItemWID / 2, candidateItemHEI / 2,
            this.circleRadius, e);
    }

    doSelectWrongTwinkle() {
        Laya.Tween.to(this.viewSelect, { alpha: 1 }, 400, Laya.Ease.quartOut, null, 0);
        Laya.Tween.from(this, { x: this.x - candidateItemWID * 0.1 }, 600, Laya.Ease.elasticOut, null, 300);
        Laya.Tween.to(this.viewSelect, { alpha: 0 }, 400, Laya.Ease.quartOut, null, 800);
    }

    checkIsLight() {
        let rgbs = this.colorToRgb(this.dataSource.color)
        return (
            0.213 * rgbs[0] +
            0.715 * rgbs[1] +
            0.072 * rgbs[2] >
            255 / 2
        );
    }

    colorToRgb (str) {
        // 16进制颜色值的正则
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        // 把颜色值变成小写
        var color = str.toLowerCase();
        if (reg.test(color)) {
          // 如果只有三位的值，需变成六位，如：#fff => #ffffff
          if (color.length === 4) {
            var colorNew = "#";
            for (var i = 1; i < 4; i += 1) {
              colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
            }
            color = colorNew;
          }
          // 处理六位的颜色值，转为RGB
          var colorChange = [];
          for (var i = 1; i < 7; i += 2) {
            colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
          }
        //   return "RGB(" + colorChange.join(",") + ")";
            return colorChange;
        } else {
          return color;
        }
      };
}